const express = require("express");
const router = express.Router();
const path = require('path');
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const axios = require("axios");
const CryptoJS = require("crypto-js");
const crypto = require("crypto");
const config = require("../config");
const { content } = require("googleapis/build/src/apis/content/index.js");
const apiKey = process.env.OPENAI_API_KEY;
const msgUtils = require("../utils/feishu.js");

// 配置 multer 的存储设置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件上传目录
        cb(null, "/home/wwwroot/default/beautyImages");
    },
    filename: function (req, file, cb) {
        // 生成文件名
        cb(null, Date.now() + "-" + file.originalname);
    },
});

const upload = multer({ storage: storage });

// 创建文件上传的 POST 接口
router.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;
    const { pk } = req.body;
    if (!file) {
        return res.status(400).send("请上传一个文件。");
    }
    let fileUrl = ''
    //安卓qrcode 放ins2服务器

    fileUrl = `https://insdoss.freeapptools.com/beautyImages/${file.filename}`;



    // 返回文件存储地址
    res.send({
        code: 0,
        message: "success",
        fileUrl: fileUrl,
    });
});

router.post('/submitSurveyResponse', async (req, res) => {
    const { language, country, isp, questionnaireResponses, app_version } = req.body
    let content = {}
    content.id = utils.createId();
    content.language = language;
    content.country = country;
    content.isp = isp;
    content.questionnaireResponses = questionnaireResponses;
    content.app_version = app_version;
    content.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql("iptv_questionnaire", content);

    let result = await utils.query(text, values);
    if (result.affectedRows == 1) {
        res.send({
            code: 0,
            msg: "success",
        });

    }
})

router.post('/getList', async (req, res) => {
    const { dateRange, country, language } = req.body;
    let sql = `SELECT * FROM iptv_questionnaire WHERE 1=1`;
    let params = [];

    if (country) {
        sql += " AND country = ?";
        params.push(country);
    }
    if (language) {
        sql += " AND language = ?";
        params.push(language);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');

        sql += ` AND update_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    try {
        const results = await mysqlQuery(sql, params);

        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        console.error('Error fetching token usage data:', error);
        res.status(500).send('Internal Server Error');
    }
});
//获取语种列表
router.post("/getLanguageList", async (req, res) => {
    let sql = `SELECT language FROM iptv_questionnaire GROUP BY language;`;
    let result = await mysqlQuery(sql, [])
    res.send(
        utils.returnData({
            data: result,
        })
    );
});
router.post("/getCountryList", async (req, res) => {
    let sql = `SELECT country FROM iptv_questionnaire GROUP BY country;`;
    let result = await mysqlQuery(sql, [])
    res.send(
        utils.returnData({
            data: result,
        })
    );
});
async function mysqlQuery(sql, arr) {

    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {

            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
router.post('/generateSign', async (req, res) => {
    const { user_id, role_id, timestamp, token } = req.body;
    let params = {
        user_id: Number(user_id),
        role_id: Number(role_id),
        timestamp: String(timestamp)
    };
    // 去除 sign 字段，node这里无自动sign
    let keys = Object.keys(params).sort();
    let kvArr = keys.map(key => `${key}=${params[key]}`);
    const signStr = kvArr.join('&');
    // 2. 拼接 token (即 salt)
    const finStr = signStr + token;
    // 3. md5哈希
    const sign = crypto.createHash('md5').update(finStr).digest('hex');
    res.send({ sign: sign })
})
router.post('/categoryList', async (req, res) => {
    try {
        // 前端将 user_id, role_id, timestamp 之类参数带到这里
        const { user_id, role_id, timestamp, sign, token } = req.body.auth_info;
        const resp = await axios.post(
            'https://open-api.bytedrama.com/bytedrama/open/api/sp/category/list',
            {
                auth_info: { user_id, role_id, timestamp, sign, token }
            },
            {
                headers: {
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Connection': 'Keep-Alive',
                    'Content-Type': 'application/json',
                    'User-Agent': 'okhttp/4.12.0',
                    'token': token,
                }
            }
        );
        res.json(resp.data);
    } catch (e) {
        res.status(500).json({ code: 500, msg: 'bytedrama category proxy error', error: e.toString() });
    }
});
// Node中转获取媒体列表
router.post('/mediaList', async (req, res) => {
    try {
        const { auth_info, page_info, controller } = req.body;
        const { user_id, role_id, timestamp, sign, token } = auth_info;
        const resp = await axios.post(
            'https://open-api.bytedrama.com/bytedrama/open/api/sp/file/list',
            {
                auth_info: { user_id, role_id, timestamp, sign, token },
                page_info,
                controller
            },
            {
                headers: {
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Connection': 'Keep-Alive',
                    'Content-Type': 'application/json',
                    'User-Agent': 'okhttp/4.12.0',
                    'token': token,
                }
            }
        );
        res.json(resp.data);
    } catch (e) {
        res.status(500).json({ code: 500, msg: 'bytedrama media proxy error', error: e.toString() });
    }
});
// 文件下载或播放接口 - 代理
router.post('/fileDownload', async (req, res) => {
    try {
        // 前端传 user_id, role_id, token, file_id, selectedEpisode
        const { auth_info, controller } = req.body;
        const timestamp = Math.floor(Date.now() / 1000).toString();
        const bytedramaRes = await axios.post(
            'https://open-api.bytedrama.com/bytedrama/open/api/sp/file/download',
            {
                auth_info: auth_info,
                controller: controller
            },
            {
                headers: {
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Connection': 'Keep-Alive',
                    'Content-Type': 'application/json',
                    'User-Agent': 'okhttp/4.12.0',
                }
            }
        );
        res.json(bytedramaRes.data);
    } catch (err) {
        res.status(500).json({ code: 500, msg: 'proxy fileDownload error', error: err.toString() });
    }
});
router.get('/proxyDownload', async (req, res) => {
    const fileUrl = req.query.url; // 你要下载的远程play_url
    const filename = req.query.name || 'video.mp4';
    try {
        const response = await axios.get(fileUrl, { responseType: 'stream' });
        res.setHeader('Content-Type', 'video/mp4');
        res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
        response.data.pipe(res);
    } catch (err) {
        res.status(500).send('Failed to download');
    }
});
 
router.post('/reportAppInfo', (req, res) => {
    const reportArr = req.body; // 这里直接拿json array
    if (!Array.isArray(reportArr) || reportArr.length === 0) {
        return res.json({ code: -1, msg: '参数不完整' });
    }

    // 获取当天日期字符串
    const now = new Date();
    const yyyy = now.getFullYear();
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()  ).padStart(2, '0'); // 注意这里减5天
    const dateStr = `${yyyy}-${mm}-${dd}`;

    // 组装sql和参数
    let todo = reportArr
        .map((item, index) => {
            if (!item || !item.lang || !item.ids) return null;
            // 去除多余空格
            const lang = String(item.lang).trim();
            const idsStr = String(item.ids).split(',').map(s => s.trim()).filter(Boolean).join(',');
            if (!lang || !idsStr) return null;
            return [dateStr, lang, idsStr, index]; // 添加索引作为排序依据
        })
        .filter(Boolean);

    if (!todo.length) {
        return res.json({ code: -1, msg: '参数内容无效' });
    }

    // 构造批量插入/更新sql（MySQL支持ON DUPLICATE KEY UPDATE）
    const valuesSql = todo.map(() => "(?,?,?,?)").join(",");
    const sql = `INSERT INTO app_video_report (record_date, language, ids, sort_order)
                 VALUES ${valuesSql}
                 ON DUPLICATE KEY UPDATE ids=VALUES(ids), sort_order=VALUES(sort_order)`;

    // 拉直参数数组
    const flatArgs = [].concat(...todo);

    pool.query(sql, flatArgs, async (err, result) => {
        if (err) return res.json({ code: -1, msg: '数据库写入失败', err });
        try {
            let token = await msgUtils.getTenantAccessToken();
            let msg_type = "interactive";
            let chatid = "oc_35448f3b1cb786c7ea070fec677ef8f0";
            // let chatid = "oc_300d536417e7a4d6a47c27bc43b00bb0";//自己
            let now = moment(new Date()).tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss");

            let cardContent = `\n[打开运营后台](https://insdoss.freeapptools.com/#/video/material)\n**上报时间**：${now}\n\n<at id="ou_d28dbe6a873320f1c9f7789e7d306b2b"></at>`;

            let contentMsg = {
                schema: "2.0",
                config: {
                    update_multi: true,
                    style: {
                        text_size: {
                            normal_v2: {
                                default: "normal",
                                pc: "normal",
                                mobile: "heading"
                            }
                        }
                    }
                },
                body: {
                    direction: "vertical",
                    padding: "12px 12px 12px 12px",
                    elements: [
                        {
                            tag: "column_set",
                            columns: [
                                {
                                    tag: "column",
                                    width: "weighted",
                                    elements: [
                                        {
                                            tag: "markdown",
                                            content: cardContent,
                                            text_align: "left",
                                            text_size: "normal_v2",
                                            margin: "0px 0px 0px 0px"
                                        }
                                    ],
                                    vertical_align: "top",
                                    weight: 1
                                }
                            ]
                        }
                    ]
                },
                header: {
                    title: {
                        tag: "plain_text",
                        content: `【热门短剧更新啦】`
                    },
                    template: "turquoise",
                    padding: "12px 12px 12px 12px"
                }
            };
            let jsonString = JSON.stringify(contentMsg);
            await msgUtils.sendMessage(chatid, msg_type, jsonString, token);

            // 接口返回
            res.json({ code: 0, msg: 'success' });
        } catch (e) {
            res.json({ code: 0, msg: '上报成功，飞书通知失败', error: String(e) });
        }
    });
});



router.post('/getReportDates', (req, res) => {
    const sql = `
        SELECT DATE_FORMAT(record_date, "%Y-%m-%d") AS record_date, language, ids 
        FROM app_video_report 
        ORDER BY record_date DESC, sort_order ASC
    `;
    pool.query(sql, [], (err, results) => {
        if (err) return res.json({ code: -1, msg: '数据库错误', err });

        // 按日期聚合
        const map = {};
        results.forEach(row => {
            if (!map[row.record_date]) map[row.record_date] = [];
            map[row.record_date].push({
                language: row.language,
                ids: row.ids // 直接原样返回
            });
        });
        const data = Object.keys(map).sort().reverse().map(date => ({
            date,
            list: map[date]
        }));

        res.json({ code: 0, data });
    });
});






module.exports = router;
